package test.redis.hongbao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class App {
	
	static HongBao hb = new HongBao();
	static int num = 15;
	
	public static void main(String[] args) throws InterruptedException {
		List list = init(100, num);
		
		hb.setIndex(0);
		hb.setInList(list);
		hb.setOutList(Collections.synchronizedList(new ArrayList()));
		System.err.println("开抢！！");
		for(int i=0;i<100;i++) {
			new Thread() {
				public void run() {
					try {
						getHongBao("用户"+UUID.randomUUID());
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				};
			}.start();
		}
		Thread.sleep(2000);
		System.err.println("共有"+hb.getOutList().size()+"人抢到红包");
		if(hb.getOutList().size()>num) {
			System.err.println("有人冒领！！");
		}
	}
	
	public static List init(int total, int num) {
		Random r = new Random();
		double sum = (double)total;
		double permax = sum/num*2;
		
		int maxrate = ((Double)(permax*10000/sum)).intValue();
		System.out.println(maxrate);
		
		System.out.println("每人能够分得的最大金额为"+permax);
		double left = sum;
		List list = new ArrayList();
		int index = 0;
		for(;;) {
			index++;
			double rate = (r.nextInt(maxrate)+1)/10000d;
			System.out.println(rate);
			double money = sum*rate;
			System.out.print("第"+index+"次分配，本次随机分配的金额为"+money+",");
			if(list.size()==num-1) {
				System.out.println("当前为最后一次分配");
				list.add(left);
				break;
			} else if(money<0.1d) {
				System.out.println("小于最小金额");
				continue;
			} else if(money>left) {
				System.out.println("超过可用余额");
				continue;
			} else {
				System.out.println("分配成功");
				left = left - money;
				list.add(money);
			}
		}
		System.out.println("-----------------------------------------------------");
		for(int i=0;i<list.size();i++) {
			System.out.println(list.get(i));
		}
		System.out.println("-----------------------------------------------------");
		return list;
	}
	
	public static void getHongBao(String name) throws InterruptedException {
		int index = hb.getIndex();
		//Thread.sleep(1);
		if(index==num) {
			System.out.println("红包已经抢完了");
		} else {
			hb.setIndex(index+1);
			List list = hb.getOutList();
			list.add(name);
			hb.setOutList(list);
			System.out.println(name+"抢到红包，金额为"+hb.getInList().get(index));
		}
	}

}
